#创建一个PHP类，

import subprocess
import json

class PHP(object):
    """This class provides a stupid simple interface to PHP code."""
    
    def __init__(self, filenameAddr):
        self.filenameAddr = filenameAddr #执行的php文件

    def __submit(self):
        proc = subprocess.Popen(
                    #["php",self.filenameAddr],  #适合window
                    "php "+ self.filenameAddr,  # 适合linux 
                    stdin=subprocess.PIPE,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    shell=True
                    )
        #proc.stdin.write('<?php\n'.encode())
        #proc.stdin.write('echo json_encode('.encode())
        #proc.stdin.write(code.encode())
        #proc.stdin.write(')?>\n'.encode())
        out,err=proc.communicate()
        out = json.loads(out.decode())  #返回的是字符串,转为json对象
        return out

    def get_raw(self, code):
        """Given a code block, invoke the code and return the raw result as a string."""
        out = self.__submit(code)
        return out

    def get(self):
        """Given a code block that emits json, invoke the code and interpret the result as a Python value."""
        out = self.__submit()
        return out

    def get_one(self, code):
        """Given a code block that emits multiple json values (one per line), yield the next value."""
        out = self.__submit(code)
        for line in out:
            line = line.strip()
            if line:
                yield json.loads(line)
